<template>
  <Select
    @dropdown-visible-change="handleFetch"
    v-bind="$attrs"
    @change="handleChange"
    :options="getOptions"
    :filter-option="filterOption ? filterOption : defaultFilter"
    v-model:value="innerValue"
  >
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
    <template #suffixIcon v-if="loading">
      <LoadingOutlined spin />
    </template>
    <template #notFoundContent v-if="loading">
      <span>
        <LoadingOutlined spin class="mr-1" />
        {{ t('component.form.apiSelectNotFound') }}
      </span>
    </template>
  </Select>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, computed, unref, watch } from 'vue';
import { Select } from 'ant-design-vue';
import { useAttrs } from '@/hooks/core/useAttrs';
import { get, omit } from 'lodash-es';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { useI18n } from '@/hooks/web/useI18n';
import { propTypes } from '@/utils/propTypes';
import { getDictList } from '@/utils/cache/busCache';
import { isArray, isString } from 'lodash-es';
import { getData } from '@/utils/http/axios/component';
type OptionsItem = { label: string; value: string; disabled?: boolean };

export default defineComponent({
  name: 'ApiSelect',
  components: {
    Select,
    LoadingOutlined,
  },
  inheritAttrs: false,
  props: {
    value: [Array, Object, String, Number],
    numberToString: propTypes.bool,
    api: {
      type:
        String ||
        ([Function] as PropType<(arg?: Recordable) => Promise<OptionsItem[]>>),
      default: null,
    },
    options: {
      type: Array,
    },
    // api params
    params: propTypes.any.def({}),
    // support xxx.xxx.xx
    resultField: propTypes.string.def(''),
    labelField: propTypes.string.def('label'),
    valueField: propTypes.string.def('value'),
    immediate: propTypes.bool.def(true),
    alwaysLoad: propTypes.bool.def(false),
    dictCode: propTypes.string.def(''),
    exclude: propTypes.array.def([]),
    optional: propTypes.string.def(''),
    filterOption: propTypes.func.def(),
  },
  emits: ['options-change', 'change', 'update:value'],
  setup(props, { emit }) {
    const innerValue = ref(props?.value);
    const _options = ref<OptionsItem[]>([]);
    const loading = ref(false);
    // 首次是否加载过了
    const isFirstLoaded = ref(false);
    const attrs = useAttrs();
    const label = ref('');
    const { t } = useI18n();
    const defaultFilter = (inputV, option) => {
      return (
        option.label.toLowerCase().indexOf(inputV.toLowerCase()) >= 0
      );
    };
    const getOptions = computed(() => {
      const { labelField, valueField, numberToString } = props;
      const opts = (unref(_options).length
        ? unref(_options)
        : props.options) as unknown as Recordable[];
      if (!opts || !opts.length) return [];
      let data = opts
        .reduce((prev, next: Recordable) => {
          if (next) {
            const value = get(next, valueField);
            prev.push({
              ...omit(next, [labelField, valueField]),
              label: get(next, labelField),
              value: numberToString ? `${value}` : value,
            });
          }
          return prev;
        }, [] as OptionsItem[])
        // 排除选项
        .filter((op) => props.exclude.indexOf(op.value) === -1)
        .filter((op) => {
          if (props.optional) {
            return props.optional == op.data?.ext2;
          } else {
            return op;
          }
        });
      return data;
    });
    const getLabel = () => {
      setTimeout(() => {
        const { labelField, valueField, options } = props;
        const opts = (options || _options.value) as Array<Recordable>;
        if (!opts || opts.length === 0) return '';
        if (innerValue.value && isString(innerValue.value)) {
          const findOption = opts.find(
            (option) => option[valueField] + '' === innerValue.value + '',
          );
          label.value = findOption ? findOption[labelField] : '';
        }
        if (innerValue.value && isArray(innerValue.value)) {
          const v = innerValue.value as Array<Object>;
          const findOptions = opts.filter(
            (option) => v.indexOf(option[valueField] + '') > -1,
          );
          label.value =
            findOptions && findOptions.length
              ? findOptions.map((o) => o[labelField]).join(',')
              : '';
        }
      });
    };
    watch(
      () => _options.value,
      (v) => {
        if (v) getLabel();
      },
      {
        immediate: true,
      },
    );
    watch(
      () => props?.value,
      (n, o) => {
        innerValue.value = n;
        getLabel();
      },
    );
    watch(
      () => innerValue.value,
      (v) => {
        emit('update:value', v);
      },
      {
        immediate: true,
      },
    );

    watch(
      () => props.params,
      () => {
        fetch();
      },
      { deep: true, immediate: props.immediate },
    );
    watch(
      () => props.dictCode,
      (v) => {
        if (v) _options.value = getDictList(v);
      },
    );
    async function fetch() {
      if (props.dictCode) {
        _options.value = getDictList(props.dictCode);
        emitChange();
        return;
      }
      const api = props.api;
      if (!api || loading.value) return;
      _options.value = [];
      try {
        loading.value = true;
        const res = await getData(api, props.params);
        isFirstLoaded.value = true;
        if (Array.isArray(res)) {
          _options.value = res;
          emitChange();
          return;
        } else {
          _options.value = res.rows;
        }
        if (props.resultField) {
          _options.value = get(res, props.resultField) || [];
        }
        emitChange();
      } catch (error) {
        console.warn(error);
      } finally {
        loading.value = false;
      }
    }

    async function handleFetch(visible) {
      if (visible) {
        if (props.alwaysLoad) {
          await fetch();
        } else if (!props.immediate && !unref(isFirstLoaded)) {
          await fetch();
        }
      }
    }

    function emitChange() {
      emit('options-change', unref(getOptions));
    }

    function handleChange(_, ...args) {
      emit('change', innerValue.value, ...args);
    }

    return {
      innerValue,
      attrs,
      getOptions,
      getLabel,
      label,
      loading,
      defaultFilter,
      t,
      handleFetch,
      handleChange,
    };
  },
});
</script>
